#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <time.h>

#define DEVICE_PATH "/dev/contig_mmap"
#define PAGE_COUNT 4
#define BUFFER_SIZE (PAGE_COUNT * 4096)

int main() {
    int fd;
    char *map;
    int i;

    fd = open(DEVICE_PATH, O_RDWR);
    if (fd < 0) {
        perror("Failed to open device");
        return 1;
    }

    map = mmap(NULL, BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (map == MAP_FAILED) {
        perror("Failed to mmap");
        close(fd);
        return 1;
    }

	 printf("Before write: ");
    for (i = 0; i < 10; i++) {
       printf("%02x ", (unsigned char)map[BUFFER_SIZE-1-i]);
    }

    // 生成随机数据
    srand(time(NULL));
    for (i = 0; i < BUFFER_SIZE; i++) {
        map[i] = rand() % 256;
    }

    printf("\nWritten random data to mapped memory\n");

    // 验证数据
    printf("First 10 bytes: ");
    for (i = 0; i < 10; i++) {
        printf("%02x ", (unsigned char)map[BUFFER_SIZE-1-i]);
    }
    printf("\n");

    munmap(map, BUFFER_SIZE);
    close(fd);
    return 0;
}
